package cn.jiedanba.cacert.tsaserver.controller;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import cn.jiedanba.cacert.common.result.ResponseResult;
import cn.jiedanba.cacert.tsaserver.service.TsaService;

/**
 * 时间戳
 * 
 * @author dell
 *
 */
@RestController
public class TsaController {

	@Autowired
	private TsaService tsaService;

	@RequestMapping(value = "/")
	public void sign(HttpServletResponse response, HttpServletRequest request) throws IOException {

		String contentType = request.getContentType();
		String contentEncoding = request.getHeader("Content-Transfer-Encoding");
		if (!request.getMethod().equalsIgnoreCase("POST")) {
			response.sendError(400);
			return;
		}

		// 不是时间戳请求类型
		if (!"application/timestamp-query".equalsIgnoreCase(contentType)) {
			response.sendError(400);
			return;
		}
		byte[] document = null;

		if ("base64".equalsIgnoreCase(contentEncoding)) {
			document = Base64.decodeBase64(getBodyData(request));
		} else {
			document = IOUtils.toByteArray(request.getInputStream());
		}

		byte[] tst = null;
		ResponseResult r = tsaService.sign(document);
		if (!r.isSuccess()) {
			response.setContentType("application/json; charset=UTF-8");
			response.getOutputStream().write(JSON.toJSONString(r).getBytes());
			return;
		}
		tst = (byte[]) r.getData();

		response.setHeader("Content-Type", "application/timestamp-reply");
		response.setHeader("Connection", "close");
		response.setHeader("content-encoding", "binary");
		response.getOutputStream().write(tst);

	}

	private static String getBodyData(HttpServletRequest request) {
		StringBuffer data = new StringBuffer();
		String line = null;
		BufferedReader reader = null;
		try {
			reader = request.getReader();
			while (null != (line = reader.readLine()))
				data.append(line);
		} catch (IOException e) {
		} finally {

		}
		return data.toString();
	}

}
